<template>
  <div ref="box">
    <slot />
  </div>
</template>
<script lang="ts" setup>
import _debounce from "lodash/debounce";
import { useActivatedExec, useActivatedEvent } from "@/hooks";

const props = withDefaults(
  defineProps<{
    mode?: "height" | "width" | "both";
  }>(),
  {
    mode: "height",
  },
);

const emits =
  defineEmits<(e: "heightChange" | "widthChange", value: number) => void>();

const box = ref<HTMLElement>();

const emitSizeChange = _debounce(() => {
  nextTick(() => {
    switch (props.mode) {
      case "height":
        emits("heightChange", box.value?.clientHeight || 0);
        break;
      case "width":
        emits("widthChange", box.value?.clientWidth || 0);
        break;
      case "both":
        emits("heightChange", box.value?.clientHeight || 0);
        emits("widthChange", box.value?.clientWidth || 0);
        break;
    }
  });
}, 16);

useActivatedExec(() => {
  emitSizeChange();
});

useActivatedEvent(
  () => {
    window.addEventListener("resize", emitSizeChange);
  },
  () => {
    window.removeEventListener("resize", emitSizeChange);
  },
);

onUpdated(() => {
  emitSizeChange();
  // console.log("onUpdated");
});

onBeforeUnmount(() => {
  emitSizeChange();
  emitSizeChange.flush();
});
</script>
